package com.zqh.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 曾庆红
 * {@code @date} 2023-10-12 23:21
 * ReentrantLock 之 tryLock
 */

public class T1 {
    Lock lock = new ReentrantLock();
    void m1(){
        try{
            lock.lock();
            for (int i = 0; i<3; i++){
                TimeUnit.SECONDS.sleep(2);
                System.out.println(i);
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    void m2(){
        boolean locked = false;
        try{
            /**
             * 无论tryLock是否会得到锁都会向下执行
             */
            locked = lock.tryLock(5,TimeUnit.SECONDS);
            System.out.println("m2 ..."+locked);
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            if(locked){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        T1 t = new T1();
        long start = System.currentTimeMillis();
        new Thread(t::m1).start();
        try{
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        new Thread(t::m2).start();
        long end  = System.currentTimeMillis();
        System.out.println("main: " + (end - start));

    }
}
